package com.crud.project.controller;

import com.crud.project.po.User;
import com.crud.project.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/main")
    public String findAllUser(@RequestParam(required=true,defaultValue="1") Integer page, Model model){
        PageHelper.startPage(page,3);
        List<User> userList=userService.findAllUser();
        PageInfo<User> pageInfo=new PageInfo<>(userList);
        model.addAttribute("user",pageInfo);
        return  "first";
    }

    @PostMapping("/main/search")
    public String search(@RequestParam(required=true,defaultValue="1") Integer page,@RequestParam("username") String username, Model model){
        if (username==null){
            PageHelper.startPage(page,3);
            List<User> userList=userService.findAllUser();
            PageInfo<User> pageInfo=new PageInfo<>(userList);
            model.addAttribute("user",pageInfo);
            return "first ::blogList";
        }
        PageHelper.startPage(page,3);
        List<User> userList=userService.findAllUserName(username);
        PageInfo<User> pageInfo=new PageInfo<>(userList);
        model.addAttribute("user",pageInfo);
        return "first ::blogList";
    }

    @GetMapping("/second")
    public String second(Model model,HttpSession httpSession){
        if (httpSession.getAttribute("user")==null){
            model.addAttribute("user",new User());
        }
        return "second";
    }

    @PostMapping("/insertUser")
    public String insertUser(User user){
            user.setDate(new Date());
            userService.insertUser(user);
        return "redirect:/main";
    }

    @GetMapping("/delete/{id}")
    public String deleteById(@PathVariable Long id){
        userService.deleteUserById(id);
        return "redirect:/main";
    }

    @GetMapping("/updateUser/{id}")
    public String updateUserById(@PathVariable Long id,Model model){
         User user=userService.findById(id);
         model.addAttribute("user",user);
        return "second";
    }

    @PostMapping("/update/{id}")
    public String update(@PathVariable Long id,User user, Model model){
        user.setDate(new Date());
        User user1=userService.findById(id);
        BeanUtils.copyProperties(user, user1);
        userService.updateUser(user1);
        return "redirect:/main";
    }
}
